<?php
namespace Boosen\Company\app\Console\Commands;

use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;

/**
* 
*/
class GoutteClient
{
	private $proxies = [];
	private $proxy_index;
	private $proxy;
	private $guzzleClient;
	private $client;
	
	public function __construct()
	{
		$this->setGuzzleClient();
		$this->setClient();
	}

	public function client()
	{
		return $this->client;
	}

	public function setClient()
	{
		$this->client = new Client();
		$this->client->setClient($this->guzzleClient);
		return $this;
	}

	private function setGuzzleClient()
	{
		$opts = ['timeout' => 30];

        if ($this->proxy) {
            $this->info('using ' . $this->proxy);
            $opts = array_merge($opts, ['proxy' => $this->proxy]);
        }

        $this->guzzleClient = new GuzzleClient($opts);
        return $this;
	}


	public function changeProxy()
	{
		$count = count($this->proxies);

		while (true) {
			if ($this->proxy_index < ($count - 1)) {
				$this->proxy_index++;
				if (!$this->proxies[$this->proxy_index]) continue;
				$this->proxy = $this->proxies[$this->proxy_index];
			} elseif ($this->proxy_index == $count -1) {
				sleep(60); // a round then sleep 20s
				$this->proxy = null; // use local
				$this->proxy_index = null;
			} elseif ($this->proxy_index === null) {
				$this->proxy_index = 0;
				if (!isset($this->proxies[0])) continue;
				$this->proxy = $this->proxies[0];
			}

			break;
		}
		
		$this->setGuzzleClient();
		return $this;
	}

	public function getProxy()
	{
		return $this->proxy;
	}

	public function resetProxy()
	{
		$this->proxy = null;
		$this->setGuzzleClient();
		return $this;
	}

	public function hasProxy()
	{
		return (bool)$this->proxy;
	}

	public function unsetProxy($proxy = null)
	{
		
		if (isset($this->proxies[$this->proxy_index])) {
			unset($this->proxies[$this->proxy_index]);
			return true;
		}

		return false;
		
	}

	public function proxyCount()
	{
		return count($this->proxies);
	}

	public static function getInstance()
	{
		return new self();
	}
}